package org.nicholasjones.radiocontroller.web.dao;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.nicholasjones.radiocontroller.web.model.BaseEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import java.io.Serializable;
import java.util.Collection;
import java.util.Date;

public abstract class AbstractHibernateDAO<T extends BaseEntity> extends HibernateDaoSupport {
    private Class<T> clazz;

    public AbstractHibernateDAO(Class<T> clazz) {
        this.clazz = clazz;
    }

    @SuppressWarnings("unchecked")
    public T findById(Serializable id) {
        return (T) getSession().get(clazz, id);
    }

    @SuppressWarnings("unchecked")
    public Collection<T> findAll() {
        return getCriteria().list();
    }

    public Criteria getCriteria() {
        return getSession().createCriteria(clazz);
    }

    public void create(T value) {
        getSession().save(value);
    }

    public void upsert(T value) {
        if (value.getId() == null) {
            value.setCreatedAt(new Date());
        }
        getSession().saveOrUpdate(value);
        getSession().flush();
    }

    public void delete(T value) {
        getSession().delete(value);
    }

    @Autowired
    public void setParentSessionFactory(@Qualifier("sessionFactory") SessionFactory sessionFactory) {
        setSessionFactory(sessionFactory);
    }
}
